package com.seu.vcampus.view;

import com.seu.vcampus.client.VCampusClient;
import com.seu.vcampus.message.Message;
import com.seu.vcampus.util.UIStyleUtil;
import com.seu.vcampus.vo.User;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * 现代化用户管理面板
 * 采用Material Design风格，提供用户管理功能
 * 
 * @author 虚拟校园开发团队
 * @since 2.0.0
 */
public class ModernUserManagementPanel extends JPanel {
    private VCampusClient client;
    private User currentUser;
    
    // 表格组件
    private JTable userTable;
    private DefaultTableModel tableModel;
    
    // 搜索组件
    private JTextField searchField;
    private JButton searchButton;
    private JButton clearButton;
    private JComboBox<String> typeComboBox;
    private JComboBox<String> statusComboBox;
    
    // 操作按钮
    private JButton refreshButton;
    private JButton addButton;
    private JButton editButton;
    private JButton deleteButton;
    private JButton activateButton;
    
    // 状态标签
    private JLabel statusLabel;
    private JLabel userCountLabel;
    
    public ModernUserManagementPanel(VCampusClient client, User user) {
        this.client = client;
        this.currentUser = user;
        
        UIStyleUtil.setupGlobalStyle();
        initializeComponents();
        setupLayout();
        setupEventHandlers();
        loadUsers();
    }
    
    /**
     * 初始化所有组件
     */
    private void initializeComponents() {
        setLayout(new BorderLayout());
        setBackground(UIStyleUtil.BACKGROUND_COLOR);
        setBorder(new EmptyBorder(20, 20, 20, 20));
        
        // 初始化表格
        setupTables();
        
        // 搜索组件
        searchField = UIStyleUtil.createModernTextField("搜索用户名、邮箱、电话...");
        searchButton = UIStyleUtil.createPrimaryButton("搜索");
        clearButton = UIStyleUtil.createSecondaryButton("清空");
        
        // 类型选择
        String[] types = com.seu.vcampus.util.UserTypeUtil.getAllUserTypeTexts();
        typeComboBox = new JComboBox<>(types);
        typeComboBox.insertItemAt("全部类型", 0);
        typeComboBox.setSelectedIndex(0);
        typeComboBox.setFont(UIStyleUtil.BODY_FONT);
        typeComboBox.setBackground(Color.WHITE);
        
        // 状态选择
        String[] statuses = {"全部状态", "启用", "禁用"};
        statusComboBox = new JComboBox<>(statuses);
        statusComboBox.setFont(UIStyleUtil.BODY_FONT);
        statusComboBox.setBackground(Color.WHITE);
        
        // 操作按钮
        refreshButton = UIStyleUtil.createSecondaryButton("刷新");
        addButton = UIStyleUtil.createSuccessButton("添加用户");
        editButton = UIStyleUtil.createPrimaryButton("编辑用户");
        deleteButton = UIStyleUtil.createDangerButton("删除用户");
        activateButton = UIStyleUtil.createWarningButton("启用/禁用");
        
        // 状态标签
        statusLabel = UIStyleUtil.createModernLabel("就绪", UIStyleUtil.BODY_FONT, UIStyleUtil.SECONDARY_COLOR);
        userCountLabel = UIStyleUtil.createModernLabel("用户: 0", UIStyleUtil.BODY_FONT, UIStyleUtil.PRIMARY_COLOR);
    }
    
    /**
     * 设置表格
     */
    private void setupTables() {
        String[] columns = {"用户ID", "用户名", "邮箱", "电话", "用户类型", "状态", "创建时间"};
        tableModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        userTable = new JTable(tableModel);
        userTable.setFont(UIStyleUtil.BODY_FONT);
        userTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        userTable.getTableHeader().setBackground(UIStyleUtil.LIGHT_COLOR);
        userTable.getTableHeader().setForeground(UIStyleUtil.DARK_COLOR);
        userTable.setRowHeight(35);
        userTable.setGridColor(UIStyleUtil.BORDER_COLOR);
        userTable.setSelectionBackground(new Color(66, 133, 244, 50));
        userTable.setSelectionForeground(UIStyleUtil.DARK_COLOR);
        
        // 设置列宽
        userTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        userTable.getColumnModel().getColumn(1).setPreferredWidth(100);
        userTable.getColumnModel().getColumn(2).setPreferredWidth(150);
        userTable.getColumnModel().getColumn(3).setPreferredWidth(100);
        userTable.getColumnModel().getColumn(4).setPreferredWidth(80);
        userTable.getColumnModel().getColumn(5).setPreferredWidth(50);
        userTable.getColumnModel().getColumn(6).setPreferredWidth(120);
    }
    
    /**
     * 设置布局
     */
    private void setupLayout() {
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(15, 15));
        mainPanel.setBackground(UIStyleUtil.BACKGROUND_COLOR);
        
        // 顶部搜索面板
        JPanel searchPanel = createSearchPanel();
        
        // 中部内容面板
        JPanel contentPanel = createContentPanel();
        
        // 底部状态面板
        JPanel statusPanel = createStatusPanel();
        
        mainPanel.add(searchPanel, BorderLayout.NORTH);
        mainPanel.add(contentPanel, BorderLayout.CENTER);
        mainPanel.add(statusPanel, BorderLayout.SOUTH);
        
        add(mainPanel);
    }
    
    /**
     * 创建搜索面板
     */
    private JPanel createSearchPanel() {
        JPanel searchPanel = UIStyleUtil.createCardPanel("用户管理");
        searchPanel.setLayout(new BorderLayout(15, 15));
        
        // 使用GridBagLayout来更好地控制布局
        JPanel searchArea = new JPanel(new GridBagLayout());
        searchArea.setOpaque(false);
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        
        // 搜索区域 - 第一行
        gbc.gridx = 0; gbc.gridy = 0;
        JLabel searchLabel = new JLabel("搜索:");
        searchLabel.setForeground(Color.BLACK);
        searchArea.add(searchLabel, gbc);
        
        gbc.gridx = 1; gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        searchArea.add(searchField, gbc);
        
        gbc.gridx = 2; gbc.gridy = 0;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        searchArea.add(searchButton, gbc);
        
        gbc.gridx = 3; gbc.gridy = 0;
        searchArea.add(clearButton, gbc);
        
        // 类型和状态选择 - 第二行
        gbc.gridx = 0; gbc.gridy = 1;
        JLabel typeLabel = new JLabel("类型:");
        typeLabel.setForeground(Color.BLACK);
        searchArea.add(typeLabel, gbc);
        
        gbc.gridx = 1; gbc.gridy = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        searchArea.add(typeComboBox, gbc);
        
        gbc.gridx = 2; gbc.gridy = 1;
        JLabel statusLabel2 = new JLabel("状态:");
        statusLabel2.setForeground(Color.BLACK);
        searchArea.add(statusLabel2, gbc);
        
        gbc.gridx = 3; gbc.gridy = 1;
        searchArea.add(statusComboBox, gbc);
        
        // 操作区域
        JPanel actionArea = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        actionArea.setOpaque(false);
        actionArea.add(refreshButton);
        actionArea.add(addButton);
        actionArea.add(editButton);
        actionArea.add(deleteButton);
        actionArea.add(activateButton);
        
        searchPanel.add(searchArea, BorderLayout.WEST);
        searchPanel.add(actionArea, BorderLayout.EAST);
        
        return searchPanel;
    }
    
    /**
     * 创建内容面板
     */
    private JPanel createContentPanel() {
        JPanel contentPanel = UIStyleUtil.createCardPanel("用户列表");
        contentPanel.setLayout(new BorderLayout());
        
        JScrollPane scrollPane = UIStyleUtil.createModernScrollPane(userTable);
        contentPanel.add(scrollPane, BorderLayout.CENTER);
        
        return contentPanel;
    }
    
    /**
     * 创建状态面板
     */
    private JPanel createStatusPanel() {
        JPanel statusPanel = new JPanel(new BorderLayout());
        statusPanel.setOpaque(false);
        statusPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
        
        JPanel leftStatus = new JPanel(new FlowLayout(FlowLayout.LEFT));
        leftStatus.setOpaque(false);
        leftStatus.add(statusLabel);
        
        JPanel rightStatus = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        rightStatus.setOpaque(false);
        rightStatus.add(userCountLabel);
        
        statusPanel.add(leftStatus, BorderLayout.WEST);
        statusPanel.add(rightStatus, BorderLayout.EAST);
        
        return statusPanel;
    }
    
    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        // 搜索功能
        searchButton.addActionListener(e -> performSearch());
        clearButton.addActionListener(e -> clearSearch());
        
        // 回车键搜索
        searchField.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    performSearch();
                }
            }
        });
        
        // 按钮事件
        refreshButton.addActionListener(e -> refreshData());
        addButton.addActionListener(e -> addUser());
        editButton.addActionListener(e -> editUser());
        deleteButton.addActionListener(e -> deleteUser());
        activateButton.addActionListener(e -> toggleUserStatus());
    }
    
    /**
     * 加载初始数据
     */
    private void loadUsers() {
        refreshData();
    }
    
    /**
     * 刷新数据
     */
    private void refreshData() {
        statusLabel.setText("正在加载用户...");
        
        new Thread(() -> {
            try {
                loadAllUsers();
                
                SwingUtilities.invokeLater(() -> {
                    statusLabel.setText("用户加载完成");
                    updateStatusCounts();
                });
            } catch (Exception e) {
                SwingUtilities.invokeLater(() -> {
                    statusLabel.setText("用户加载失败: " + e.getMessage());
                    JOptionPane.showMessageDialog(this, "加载用户失败: " + e.getMessage(), 
                                                 "错误", JOptionPane.ERROR_MESSAGE);
                });
            }
        }).start();
    }
    
    /**
     * 加载所有用户数据
     */
    private void loadAllUsers() throws Exception {
        Message request = new Message(Message.Type.GET_USER_REQUEST, "all");
        Message response = client.sendMessage(request);
        
        if (response.isSuccess()) {
            List<?> payload = (List<?>) response.getPayload();
            List<User> users = new ArrayList<>();
            for (Object obj : payload) {
                if (obj instanceof User) {
                    users.add((User) obj);
                }
            }
            
            SwingUtilities.invokeLater(() -> {
                updateUserTable(users);
                statusLabel.setText("用户加载完成");
            });
        } else {
            SwingUtilities.invokeLater(() -> {
                statusLabel.setText("用户加载失败: " + response.getErrorMessage());
                JOptionPane.showMessageDialog(this, "加载用户失败: " + response.getErrorMessage(), 
                                            "错误", JOptionPane.ERROR_MESSAGE);
            });
        }
    }
    
    /**
     * 执行搜索
     */
    private void performSearch() {
        String keyword = searchField.getText().trim();
        String type = typeComboBox.getSelectedItem().toString();
        String status = statusComboBox.getSelectedItem().toString();
        
        if (keyword.isEmpty() && type.equals("全部类型") && status.equals("全部状态")) {
            refreshData();
            return;
        }
        
        statusLabel.setText("正在搜索...");
        
        new Thread(() -> {
            try {
                // 构建搜索参数
                Object[] searchParams = new Object[]{keyword, type, status};
                Message request = new Message(Message.Type.GET_USER_REQUEST);
                request.setPayload(searchParams);
                
                Message response = client.sendMessage(request);
                
                if (response.isSuccess()) {
                    List<?> payload = (List<?>) response.getPayload();
                    List<User> users = new ArrayList<>();
                    for (Object obj : payload) {
                        if (obj instanceof User) {
                            users.add((User) obj);
                        }
                    }
                    
                    SwingUtilities.invokeLater(() -> {
                        updateUserTable(users);
                        statusLabel.setText("搜索完成，找到 " + users.size() + " 个用户");
                    });
                } else {
                    SwingUtilities.invokeLater(() -> {
                        statusLabel.setText("搜索失败: " + response.getErrorMessage());
                        JOptionPane.showMessageDialog(this, "搜索失败: " + response.getErrorMessage(), 
                                                    "错误", JOptionPane.ERROR_MESSAGE);
                    });
                }
                
            } catch (Exception e) {
                SwingUtilities.invokeLater(() -> {
                    statusLabel.setText("搜索失败: " + e.getMessage());
                    JOptionPane.showMessageDialog(this, "搜索失败: " + e.getMessage(), 
                                                "错误", JOptionPane.ERROR_MESSAGE);
                });
            }
        }).start();
    }
    
    /**
     * 清空搜索
     */
    private void clearSearch() {
        searchField.setText("");
        typeComboBox.setSelectedIndex(0);
        statusComboBox.setSelectedIndex(0);
        refreshData();
    }
    
    /**
     * 更新用户表格
     */
    private void updateUserTable(List<User> users) {
        tableModel.setRowCount(0);
        for (User user : users) {
            Object[] row = {
                user.getUserId(),
                user.getUsername(),
                user.getEmail() != null ? user.getEmail() : "",
                user.getPhone() != null ? user.getPhone() : "",
                getUserTypeText(user.getUserType()),
                user.isActive() ? "启用" : "禁用",
                user.getCreateTime() != null ? user.getCreateTime().toString() : ""
            };
            tableModel.addRow(row);
        }
        updateStatusCounts();
    }
    
    /**
     * 更新状态计数
     */
    private void updateStatusCounts() {
        userCountLabel.setText("用户: " + tableModel.getRowCount());
    }
    
    /**
     * 添加用户
     */
    private void addUser() {
        UserDialog dialog = new UserDialog((JFrame) SwingUtilities.getWindowAncestor(this), null);
        dialog.setVisible(true);
        
        if (dialog.isConfirmed()) {
            User newUser = dialog.getUser();
            new Thread(() -> {
                try {
                    Message request = new Message(Message.Type.REGISTER_REQUEST);
                    request.setPayload(newUser);
                    Message response = client.sendMessage(request);
                    
                    SwingUtilities.invokeLater(() -> {
                        if (response.isSuccess()) {
                            JOptionPane.showMessageDialog(this, "用户添加成功", 
                                                        "成功", JOptionPane.INFORMATION_MESSAGE);
                            refreshData();
                        } else {
                            JOptionPane.showMessageDialog(this, "添加失败: " + response.getErrorMessage(), 
                                                        "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    });
                } catch (Exception e) {
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this, "添加失败: " + e.getMessage(), 
                                                    "错误", JOptionPane.ERROR_MESSAGE);
                    });
                }
            }).start();
        }
    }
    
    /**
     * 编辑用户
     */
    private void editUser() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要编辑的用户", 
                                        "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String userId = tableModel.getValueAt(selectedRow, 0).toString();
        String username = tableModel.getValueAt(selectedRow, 1).toString();
        String email = tableModel.getValueAt(selectedRow, 2).toString();
        String phone = tableModel.getValueAt(selectedRow, 3).toString();
        String userTypeText = tableModel.getValueAt(selectedRow, 4).toString();
        boolean isActive = "启用".equals(tableModel.getValueAt(selectedRow, 5).toString());
        
        // 创建要编辑的用户对象
        User userToEdit = new User();
        userToEdit.setUserId(userId);
        userToEdit.setUsername(username);
        userToEdit.setEmail(email.isEmpty() ? null : email);
        userToEdit.setPhone(phone.isEmpty() ? null : phone);
        userToEdit.setUserType(getUserTypeFromText(userTypeText));
        userToEdit.setActive(isActive);
        
        UserDialog dialog = new UserDialog((JFrame) SwingUtilities.getWindowAncestor(this), userToEdit);
        dialog.setVisible(true);
        
        if (dialog.isConfirmed()) {
            User updatedUser = dialog.getUser();
            new Thread(() -> {
                try {
                    Message request = new Message(Message.Type.UPDATE_USER_REQUEST);
                    request.setPayload(updatedUser);
                    Message response = client.sendMessage(request);
                    
                    SwingUtilities.invokeLater(() -> {
                        if (response.isSuccess()) {
                            JOptionPane.showMessageDialog(this, "用户更新成功", 
                                                        "成功", JOptionPane.INFORMATION_MESSAGE);
                            refreshData();
                        } else {
                            JOptionPane.showMessageDialog(this, "更新失败: " + response.getErrorMessage(), 
                                                        "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    });
                } catch (Exception e) {
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this, "更新失败: " + e.getMessage(), 
                                                    "错误", JOptionPane.ERROR_MESSAGE);
                    });
                }
            }).start();
        }
    }
    
    /**
     * 删除用户
     */
    private void deleteUser() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的用户", 
                                        "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String userId = tableModel.getValueAt(selectedRow, 0).toString();
        String username = tableModel.getValueAt(selectedRow, 1).toString();
        
        int confirm = JOptionPane.showConfirmDialog(this, 
            "确定要删除用户 " + username + " (ID: " + userId + ") 吗？", 
            "删除确认", JOptionPane.YES_NO_OPTION);
        
        if (confirm == JOptionPane.YES_OPTION) {
            new Thread(() -> {
                try {
                    Message request = new Message(Message.Type.DELETE_USER_REQUEST);
                    request.setPayload(userId);
                    Message response = client.sendMessage(request);
                    
                    SwingUtilities.invokeLater(() -> {
                        if (response.isSuccess()) {
                            JOptionPane.showMessageDialog(this, "用户删除成功", 
                                                        "成功", JOptionPane.INFORMATION_MESSAGE);
                            refreshData();
                        } else {
                            JOptionPane.showMessageDialog(this, "删除失败: " + response.getErrorMessage(), 
                                                        "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    });
                } catch (Exception e) {
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(), 
                                                    "错误", JOptionPane.ERROR_MESSAGE);
                    });
                }
            }).start();
        }
    }
    
    /**
     * 切换用户状态
     */
    private void toggleUserStatus() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要操作的用户", 
                                        "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String userId = tableModel.getValueAt(selectedRow, 0).toString();
        String username = tableModel.getValueAt(selectedRow, 1).toString();
        String email = tableModel.getValueAt(selectedRow, 2).toString();
        String phone = tableModel.getValueAt(selectedRow, 3).toString();
        String userTypeText = tableModel.getValueAt(selectedRow, 4).toString();
        String currentStatus = tableModel.getValueAt(selectedRow, 5).toString();
        
        boolean newStatus = !currentStatus.equals("启用");
        String action = newStatus ? "启用" : "禁用";
        
        int confirm = JOptionPane.showConfirmDialog(this, 
            "确定要" + action + "用户 " + username + " 吗？", 
            "状态确认", JOptionPane.YES_NO_OPTION);
        
        if (confirm == JOptionPane.YES_OPTION) {
            new Thread(() -> {
                try {
                    // 获取完整的用户信息
                    Message getUserRequest = new Message(Message.Type.GET_USER_REQUEST, userId);
                    Message getUserResponse = client.sendMessage(getUserRequest);
                    
                    if (!getUserResponse.isSuccess()) {
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(this, "获取用户信息失败: " + getUserResponse.getErrorMessage(), 
                                                        "错误", JOptionPane.ERROR_MESSAGE);
                        });
                        return;
                    }
                    
                    User userToUpdate = (User) getUserResponse.getPayload();
                    if (userToUpdate == null) {
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(this, "用户不存在", 
                                                        "错误", JOptionPane.ERROR_MESSAGE);
                        });
                        return;
                    }
                    
                    // 更新状态
                    userToUpdate.setActive(newStatus);
                    
                    // 发送更新请求
                    Message updateRequest = new Message(Message.Type.UPDATE_USER_REQUEST);
                    updateRequest.setPayload(userToUpdate);
                    Message response = client.sendMessage(updateRequest);
                    
                    SwingUtilities.invokeLater(() -> {
                        if (response.isSuccess()) {
                            JOptionPane.showMessageDialog(this, "用户状态更新成功", 
                                                        "成功", JOptionPane.INFORMATION_MESSAGE);
                            refreshData();
                        } else {
                            JOptionPane.showMessageDialog(this, "状态更新失败: " + response.getErrorMessage(), 
                                                        "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    });
                } catch (Exception e) {
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this, "状态更新失败: " + e.getMessage(), 
                                                    "错误", JOptionPane.ERROR_MESSAGE);
                    });
                }
            }).start();
        }
    }
    
    /**
     * 获取用户类型文本
     * @deprecated 使用UserTypeUtil.getUserTypeText()代替
     */
    @Deprecated
    private String getUserTypeText(User.UserType type) {
        return com.seu.vcampus.util.UserTypeUtil.getUserTypeText(type);
    }

    /**
     * 从文本获取用户类型
     * @deprecated 使用UserTypeUtil.getUserTypeFromText()代替
     */
    @Deprecated
    private User.UserType getUserTypeFromText(String text) {
        return com.seu.vcampus.util.UserTypeUtil.getUserTypeFromText(text);
    }
}